package org.jeecg.modules.activemq;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.demo.wechat.pojo.QueueMessage;
import org.jeecg.modules.santu.RobotHelper;
import org.jeecg.modules.santu.entity.TbGroupMember;
import org.jeecg.modules.santu.entity.TbMessage;
import org.jeecg.modules.santu.service.ITbGroupMemberService;
import org.jeecg.modules.santu.service.ITbMessageService;
import org.jeecg.modules.system.service.ISysDictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.jeecg.MyApplicationContextAware;

import java.util.Base64;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class Consumer {

    @Autowired
    private RobotHelper robotHelper;

    @Autowired
    private ISysDictService sysDictService;

    @JmsListener(destination = "client.invite.group.msg.queue")
    public void clientInviteGroupMsgQueue(QueueMessage queueMessage){
        System.out.println("client.invite.group.msg.queue---->");
        int repeat = queueMessage.getRepeat();
        if(repeat==QueueMessage.is_repeat){
            String content = queueMessage.getContent();
            System.out.println("invite----->" + content);
            String decoding = this.decoding(content);
            System.out.println("解密后的数据为----->" + decoding);
            try{
                JSONObject jsonObject = JSONObject.parseObject(decoding);
                System.out.println("是单条数据----->"+jsonObject);
                String avatar = jsonObject.getString("avatar");
                String groupid = jsonObject.getString("groupid");
                String inviteWxid = jsonObject.getString("inviteWxid");
                String message = jsonObject.getString("message");
                String nickname = jsonObject.getString("nickname");
                String wxid = jsonObject.getString("wxid");

                //开始插入每一条数据
                QueryWrapper<TbGroupMember> tbGroupMemberQueryWrapper = new QueryWrapper<>();
                tbGroupMemberQueryWrapper.lambda().eq(TbGroupMember::getWxid,wxid).eq(TbGroupMember::getGroupId,groupid);
                ITbGroupMemberService tbGroupMemberService = MyApplicationContextAware.getApplicationContext().getBean(ITbGroupMemberService.class);
                TbGroupMember one = tbGroupMemberService.getOne(tbGroupMemberQueryWrapper);
                if(one==null){
                    //说明该数据不存在
                    System.out.println("说明该数据不存在------->");
                    TbGroupMember tbGroupMember = new TbGroupMember();
                    tbGroupMember.setAvatar(avatar);
                    tbGroupMember.setEntryTime(new Date());
                    tbGroupMember.setGroupId(groupid);
                    tbGroupMember.setInvitedWxid(inviteWxid);
                    tbGroupMember.setNickname(nickname);
                    tbGroupMember.setTotalMoney(0.0D);
                    tbGroupMember.setMoney(0.0D);
                    tbGroupMember.setFreezeMoney(0.0D);
                    tbGroupMember.setCommission(0.0D);
                    tbGroupMember.setWxid(wxid);
                    tbGroupMember.setIsNotification(TbGroupMember.not_enable);
                    boolean save = tbGroupMemberService.save(tbGroupMember);
                    System.out.println("插入单条数据"+nickname+"状态"+save);
                }else{
                    //说明该数据已经存在
                    System.out.println("说明该数据已经存在------->");
                    one.setNickname(nickname);
                    one.setAvatar(avatar);
                    boolean b = tbGroupMemberService.updateById(one);

                    System.out.println("数据存在则更新数据------------->"+b);
                }
            }catch (Exception e){
                System.out.println("是多条数据----->");
                JSONArray array = JSONArray.parseArray(decoding);
                //System.out.println("array----->"+array);
                System.out.println("开始循环每一条数据---->");
                for (int i=0;i<array.size();i++){
                    JSONObject jsonObject = array.getJSONObject(i);
                    Integer length = jsonObject.getInteger("length");
                    if(length!=null){
                        System.out.println("length------>" + length);
                    }else{
                        System.out.println("开始寻找每一项");
                        String avatar = jsonObject.getString("avatar");
                        String groupid = jsonObject.getString("groupid");
                        String inviteWxid = jsonObject.getString("inviteWxid");
                        String message = jsonObject.getString("message");
                        String nickname = jsonObject.getString("nickname");
                        String wxid = jsonObject.getString("wxid");
                        QueryWrapper<TbGroupMember> tbGroupMemberQueryWrapper = new QueryWrapper<>();
                        tbGroupMemberQueryWrapper.lambda().eq(TbGroupMember::getWxid,wxid).eq(TbGroupMember::getGroupId,groupid);
                        ITbGroupMemberService tbGroupMemberService = MyApplicationContextAware.getApplicationContext().getBean(ITbGroupMemberService.class);
                        TbGroupMember one = tbGroupMemberService.getOne(tbGroupMemberQueryWrapper);

                        if(one==null){
                            //说明该数据不存在
                            System.out.println("数据不存在");
                            TbGroupMember tbGroupMember = new TbGroupMember();
                            tbGroupMember.setAvatar(avatar);
                            tbGroupMember.setEntryTime(new Date());
                            tbGroupMember.setGroupId(groupid);
                            tbGroupMember.setInvitedWxid(inviteWxid);
                            tbGroupMember.setNickname(nickname);
                            tbGroupMember.setWxid(wxid);
                            tbGroupMember.setTotalMoney(0.0D);
                            tbGroupMember.setMoney(0.0D);
                            tbGroupMember.setFreezeMoney(0.0D);
                            tbGroupMember.setCommission(0.0D);
                            tbGroupMember.setIsNotification(TbGroupMember.not_enable);
                            boolean save = tbGroupMemberService.save(tbGroupMember);
                            System.out.println("插入多条数据"+nickname+"状态"+save);
                        }else{
                            //说明该数据已经存在
                            System.out.println("数据存在");
                            one.setNickname(nickname);
                            one.setAvatar(avatar);
                            boolean b = tbGroupMemberService.updateById(one);

                            System.out.println("数据存在则更新数据------------->"+b);
                        }
                    }
                }
                //e.printStackTrace();
            }
        }
    }

    private String decoding(String content) {
        content = content.replaceAll("[^A-Za-z0-9+/=]", "");
        // 检查字符串长度并进行填充
        while (content.length() % 4 != 0) {
            content += "=";
        }
        byte[] decodedBytes = Base64.getDecoder().decode(content);
        String decodedStr = new String(decodedBytes);
        return decodedStr;
    }

    @JmsListener(destination = "client.synchronous.group.msg.queue")
    public void clientSynchronousGroupMsgQueue(QueueMessage queueMessage){
        int repeat = queueMessage.getRepeat();
        if(repeat==QueueMessage.is_repeat){
            String content = queueMessage.getContent();
            System.out.println("content----->"+content);
            JSONArray array = JSONArray.parseArray(content);
            for (int i = 0; i < array.size(); i++) {
                JSONObject jsonObject = array.getJSONObject(i);
                String wxid = jsonObject.getString("wxid");
                String nickname = jsonObject.getString("nickname");
                String roomid = jsonObject.getString("roomid");
                byte[] decodedBytes = Base64.getDecoder().decode(nickname);
                String decodedStr = new String(decodedBytes);
                System.out.println("解密前的字符串为-------->" + nickname);
                System.out.println("解密后的字符串为-------->" + decodedStr);
                QueryWrapper<TbGroupMember> tbGroupMemberQueryWrapper = new QueryWrapper<>();
                tbGroupMemberQueryWrapper.lambda().eq(TbGroupMember::getWxid,wxid).eq(TbGroupMember::getGroupId,roomid);
                ITbGroupMemberService tbGroupMemberService = MyApplicationContextAware.getApplicationContext().getBean(ITbGroupMemberService.class);
                TbGroupMember one = tbGroupMemberService.getOne(tbGroupMemberQueryWrapper);
                if(one==null){
                    //说明该数据不存在
                    TbGroupMember tbGroupMember = new TbGroupMember();
                    tbGroupMember.setGroupId(roomid);
                    tbGroupMember.setEntryTime(new Date());
                    tbGroupMember.setNickname(decodedStr);
                    tbGroupMember.setWxid(wxid);
                    //可提现的零钱
                    tbGroupMember.setMoney(0.0);
                    //已帮你省下
                    tbGroupMember.setTotalMoney(0.0);
                    //正在提现的零钱
                    tbGroupMember.setFreezeMoney(0.0);
                    //下级返佣
                    tbGroupMember.setCommission(0.0D);
                    boolean save = tbGroupMemberService.save(tbGroupMember);
                    System.out.println("插入群成员"+decodedStr+"状态"+save);
                }else{
                    //说明该数据已经存在
                    //数据存在则更新数据
                    System.out.println("数据存在则更新数据------>");
                    String nickname1 = one.getNickname();
                    one.setNickname(decodedStr);
                    boolean b = tbGroupMemberService.updateById(one);
                    System.out.println("之前群成员昵称是"+nickname1+"更新为"+decodedStr+"更新状态为"+b);

                }
            }
            
        }

    }


    @JmsListener(destination = "immediately.msg.queue")
    public void receiveImmediatelyMsg(QueueMessage queueMessage){
        try {
            //消息入库
            System.out.println("接收到微信消息-------->immediately.msg.queue");
            int repeat = queueMessage.getRepeat();
            System.out.println("repeat---------->"+repeat);
            List<DictModel> queueMessage1 = sysDictService.queryDictItemsByCode("queueMessage");
            String value = queueMessage1.get(0).getValue();
            int repeatNum = Integer.parseInt(value);
            System.out.println("repeatNum----------->"+repeatNum);
            if(repeat==repeatNum){
                System.out.println("queueMessage----->"+queueMessage);
                TbMessage tbMessage = new TbMessage();
                tbMessage.setMsgId(queueMessage.getMsgId());
                tbMessage.setMsgType(queueMessage.getMsgType());
                tbMessage.setMsgSource(queueMessage.getMsgSource());
                tbMessage.setMsgSourceXml(queueMessage.getMsgSourceXml());
                tbMessage.setWxid(queueMessage.getWxid());
                tbMessage.setRoomId(queueMessage.getRoomId());
                tbMessage.setContent(queueMessage.getContent());
                tbMessage.setIsRecover(TbMessage.NOT_RECOVER);
                int msgType = queueMessage.getMsgType();
                int msgSource = queueMessage.getMsgSource();
                ITbMessageService tbMessageService = MyApplicationContextAware.getApplicationContext().getBean(ITbMessageService.class);
                System.out.println("tbMessage.getId------->"+tbMessage.getId());
                tbMessage.setId(null);
                tbMessageService.save(tbMessage);
                boolean save = false;
                try {
                    save = tbMessageService.save(tbMessage);
                } catch (Exception e) {
                    System.out.println("插入重复的数据了，消息已经入库了----->");
//                    e.printStackTrace();
                }
                System.out.println("save-------->" + save);
                //=1群聊消息
                if(msgSource==1){
                    //=1群聊消息
                    robotHelper.handlerGroupTextMsg(queueMessage);
                }else if(msgSource==0){
                    // =0好友消息
                    //robotHelper.handlerFriendTextMsg(queueMessage);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("立即消息处理失败");
        }
    }

    @JmsListener(destination = "synchronization.queue")
    public void receiveSynchronizationMsg(QueueMessage queueMessage){
        try {
            System.out.println("------------------>收到群组/好友发来的消息");
            /*int repeat = queueMessage.getRepeat();
            if(repeat==QueueMessage.not_repeat){

            }*/
        } catch (Exception e) {
            e.printStackTrace();
            log.info("延时消息处理失败");
        }
    }


}
